<?php
/**
 * Created by PhpStorm.
 * User: shiyang
 * Date: 2018/12/17
 * Time: 21:34
 */

namespace App\Http\Controllers\Perm;


use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\Libraries\DataSource;
use App\Models\Role;
use App\Models\RoleUser;
use App\Models\User;
use Request;
use Response;

class UserController extends Controller
{

    public function index()
    {
        $this->authorize('user');
        return view('perm.user.index');
    }

    public function table()
    {
        $users = User::with('roles')->get();

        $users->transform(function ($user){
            return [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'last_login_at' => $user->last_login_at,
                'last_actived_at' => $user->last_actived_at,
                'state' => $user->state,
                'state_name' => User::STATES[$user->state],
                'role_name' => $user->roles->pluck('name'),
                'created_at' => $user->created_at->toDateTimeString(),
            ];
        });

        $ds = new DataSource();
        $ds->data = $users;

        return Response::json($ds);
    }

    public function create()
    {
        $this->authorize('user');
        $roles = Role::get();
        return view('perm.user.create', compact('roles'));
    }

    public function store(UserRequest $request)
    {
        $this->authorize('user');
        $input = $request->all();
        $user = User::where(['username'=>$input['username']])->first();
        if($user) {
            \Session::flash('flash_warning', '该用户名已存在！');
            return redirect()->back();
        }
        $input['password'] = bcrypt($input['password']);
        $input['state'] = User::STATE_ENABLED;
        $user = User::create($input);

        $id = $user->id;
        if (array_key_exists('role_id', $input)) {
            foreach ($input['role_id'] as $role_id) {
                $data = [
                    'role_id' => $role_id,
                    'user_id' => $id,
                ];
                RoleUser::create($data);
            }
        }
        \Session::flash('flash_success', '添加成功');
        return redirect('perm/user');
    }

    public function edit($id)
    {
        $this->authorize('user');
        $user = User::find($id);
        $roles = Role::get();
        $RoleUsers = RoleUser::where('user_id', $id)->pluck('role_id');

        if ($user == null) {
            \Session::flash('flash_warning', '无此记录');
            return redirect()->back();
        }

        return view('perm.user.edit', compact('user', 'names', 'roles', 'RoleUsers'));
    }

    public function update($id)
    {
        $this->authorize('user');
        $input = Request::all();
        $user = User::find($id);

        if ($user == null) {
            \Session::flash('flash_warning', '无此记录');
            return redirect()->back()->withInput($input);
        }

        if (!empty($input['new_password'])) {
            $input['password'] = bcrypt($input['new_password']);
        }

        if(User::isRepetition($input['name'], $input['username'], $id)) {
            \Session::flash('flash_warning', '姓名或者用户名已存在');
            return redirect()->back()->withInput($input);
        }

        $user->update($input);

        if (array_key_exists('role_id', $input)) {
            RoleUser::query()->where('user_id', $id)->delete();

            foreach ($input['role_id'] as $role_id) {
                $data = [
                    'role_id' => $role_id,
                    'user_id' => $id,
                ];
                RoleUser::create($data);
            }
        }

        \Session::flash('flash_success', '修改成功!');
        return redirect('perm/user');
    }

    public function destroy($id)
    {
        $this->authorize('user');
        $user = User::query()->find($id);
        if (! $user) {
            return response()->json([
                'code' => 404,
                'message' => '未找到记录'
            ]);
        }
        //admin用户禁止删除
        if($user->id == 1 || $user->username == 'admin') {
            return response()->json([
                'code' => 403,
                'message' => 'Forbidden'
            ]);
        }

        $flag = $user->delete();
        if($flag) {
            return response()->json([
                'code' => 200,
                'message' => 'Success'
            ]);
        }
        return response()->json([
            'code' => 500,
            'message' => '服务器异常'
        ]);
    }

    public function state($id)
    {
        $this->authorize('user');
        $state = Request::get('state');
        if(! array_key_exists($state,User::STATES)) {
            return response()->json([
                'code' => 400,
                'message' => '参数错误'
            ]);
        }
        $user = User::find($id);
        if (! $user) {
            return response()->json([
                'code' => 404,
                'message' => '未找到记录'
            ]);
        }
        //admin用户禁止操作
        if($user->id == 1 || $user->username == 'admin') {
            return response()->json([
                'code' => 403,
                'message' => 'Forbidden'
            ]);
        }
        switch ($state) {
            case User::STATE_DISABLED:
                $user->state = User::STATE_ENABLED;
                break;
            case User::STATE_ENABLED:
                $user->state = User::STATE_DISABLED;
                break;
        }
        $flag = $user->save();
        if($flag) {
            return response()->json([
                'code' => 200,
                'message' => 'Success'
            ]);
        }

        return response()->json([
            'code' => 500,
            'message' => '服务器异常'
        ]);
    }

    public function password()
    {
        $oldPassword = Request::get('old_password');
        $newPassword = Request::get('new_password');
        if(empty($oldPassword)) {
            return response()->json([
                'code' => 400,
                'message' => '原密码不能为空'
            ]);
        }
        if(empty($newPassword)) {
            return response()->json([
                'code' => 400,
                'message' => '原密码不能为空'
            ]);
        }
        if(strlen($newPassword) < 6 || strlen($newPassword) > 15) {
            return response()->json([
                'code' => 400,
                'message' => '密码长度为6-15个字符'
            ]);
        }
        if($oldPassword == $newPassword) {
            return response()->json([
                'code' => 400,
                'message' => '新密码不能和旧密码一致'
            ]);
        }

        $user = \Auth::user();
        \Log::debug('old_password:'.$oldPassword);
        \Log::debug('old_password bcrypt:'.bcrypt($oldPassword));
        \Log::debug('old0:'.$user->getAuthPassword());
        \Log::debug('old1:'.bcrypt($oldPassword));
        if(! \Hash::check($oldPassword , $user->getAuthPassword())) {
            return response()->json([
                'code' => 400,
                'message' => '原密码错误'
            ]);
        }

        $flag = $user->update(['password' => bcrypt($newPassword)]);

        if($flag) {
            \Auth::user()->refresh();
            return response()->json([
                'code' => 200,
                'message' => 'Success'
            ]);
        }
        return response()->json([
            'code' => 500,
            'message' => '服务器异常'
        ]);
    }
}
